package com.bookshop.interceptor;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.bookshop.aspect.exception.CustomException;
import com.bookshop.configuration.AuthPathConfiguration;
import com.bookshop.entity.response.TokenEnum;
import com.bookshop.util.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author g2l
 * @create 2022-08-01 10:54
 *
 * 自定义过滤器：根据url判断是否需要认证、token是否合法
 */
@Slf4j
@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Resource
    private AuthPathConfiguration authPathConfiguration;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 获取请求路径
        String uri = request.getRequestURI();

        log.info("来到了这里" + uri);
        if ("/error".equals(uri)){
            // 做了全局异常处理之后，只有404异常才能访问到/error
            throw new CustomException("页面不存在").setCode(404);
        }

        // 去请求头中获取token
        String token = request.getHeader("Authorization");

        if (StringUtils.isNotBlank(token)) {// 判断token是否为空

            // 校验token，非法、过期返回结果让用户登录，合法就放行
            TokenEnum result = JWTUtil.verify(token);

            if (result == TokenEnum.TOKEN_EXPIRE) {
                // token过期
                throw new CustomException("请去刷新token").setCode(402);
            }else if (result == TokenEnum.TOKEN_BAD) {
                // token非法
                return goLogin(response);
            }
            // 正常token
            request.setAttribute("phoneNumber", JWTUtil.getUsername(token));

            return true;
        }

        // 没有token
        return goLogin(response);
    }

    private Boolean goLogin(HttpServletResponse response) throws IOException {
        // 前端拿到后 转去登录界面
        throw new CustomException("请去登录").setCode(401);
    }

}